var totalTree;
var collapsed = 0;
var expanded = 1;
var ulIdregExp = new RegExp("^u");
var ds_id;
var ds_type;
var lang;

$(document).ready(function() {
	lang = $("#display-lang").val();
	ds_type = $("#ds_type").val();
	ds_id = $("#ds_id").val();
	
	showDocuments(0, 50, lang, true, ds_id);
	/* load */
	var dtitle;
	if(lang == 'en'){
		dtitle = "On Loading";
	}else if(lang == 'zh'){
		dtitle = "正在加载";
	}
		$("#onloading").dialog({
			bgiframe : true,
			autoOpen : false,
			draggable : false,
			closeOnEscape : false,
			closeText : false,
			resizable : false,
			width : 400,
			title : dtitle,
			modal : true
	});
	
	$("#onloading").parent().appendTo("#dialog_target");
	
	
	treeContent = $.ajax({
		url : "/sview/classTree",// "test.xml",//
		dataType : 'xml',
		type : "post",
		data : {
			state : "0",
			ds_type : $("#ds_type").val(),
			ds_id : $("#ds_id").val()
		},
		success : function(data) {
			totalTree = data;
			// alert($(data).find("named_entities").length+"abc:"+$(data).find("others").length);
			if ($(data).find("named_entities").length > 0) {
				showTopTypes(data);
			}
			if ($(data).find("others").length > 0) {
				addOthers(data);
			}
		}
	});
});
function showDocuments(start, length, lang, newFlag, ds_id) {
	if($(".centity-list").length==0){
		return;
	}
	var data = {};
	data["start"] = start;
	data["length"] = length;
	data["lang"] = lang;
	data["ds_id"] = ds_id;
	data = JSON.stringify(data);
	data = ("document=" + encodeURIComponent(data));
	$
			.ajax({
				url : "/sview/datasetDocs",
				async : true,
				data : data,
				dataType : "json",
				type : "post",
				success : function(result) {
					var lang = $("#display-lang").val();
					var array = result["result"];
					var flag = false;
					if (newFlag) {
						$(".centity-list.entity-list").html("");
					}
					if ($(".centity-list.entity-list ol").length > 0)
						flag = true;
					if (!flag) {
						var olt = $("<ol></ol>");
						$(".centity-list.entity-list").append(olt);
					}
					var ol = $(".centity-list.entity-list>ol");
					for ( var i = 0; i < array.length; i++) {
						var li = $("<li></li>");
						ol.append(li);
						var element = array[i];
						li.addClass("lentity");
						var id = element["id"];
						var div = $('<div class="sc split"></div>');
						li.append(div);
						var a = $("<a></a>");
						var href = "/sview/dataset/u";
						href = href + id;
						if(lang=="zh"){
							href += "?lang=zh";
						}
						a.attr("href", href);
						div.append(a);
						var spanName = $("<span></span>");
						var name = element["name"];
						spanName.text(name);
						spanName.addClass("entity");
						a.append(spanName);
					}
					$(".centity-list.entity-list ol li:last>div").addClass("final");
//					$(".more-container").remove();
//					if (array.length > 0) {
//						var div = $("<div class='more-container'></div>");
//						var moreDiv = $("<div class='moreDiv'></div>");
//						var a = null;
//						if (lang == 'en'){
//							a = $('<a href="javascript:void(0)"><span class="tip">Load More</span><span class="arrowDown"></span></a>');
//						}else if(lang == 'zh'){
//							a = $('<a href="javascript:void(0)"><span class="tip">更多</span><span class="arrowDown"></span></a>');
//						}
//						
//						a.bind("click", function() {
//							showDocuments(start + length, length, lang, false,
//									ds_id);
//						});
//						moreDiv.append(a);
//						div.append(moreDiv);en 
					
//						$(".entity-list").parent().append(div);
//					}
				}
			});
}
function onLoading() {
	$("#onloading").dialog("open");
}
function closeLoading() {
	$("#onloading").dialog("close");
}


function addOthers(data) {
	if(lang == 'en'){
		$("#othersUl").append(
				"<li class='others ' id='-1'>"
						+ "<a href='#others'><ins>Others</ins></a>"
						+ "</li>");
	}else if(lang == 'zh'){
		$("#othersUl").append(
				"<li class='others ' id='-1'>"
						+ "<a href='#others'><ins>其他</ins></a>"
						+ "</li>");
	}
}
//show top classes
function showTopTypes(data) {
	if(lang == 'en'){
		$("#namedEntitiesUl")
		.append(
//				"<li id=0><a href='#ne' >" 
				"<li id=0><a class='treeLiA' aimId='ne' href='javascript:void(0);' >" 
				+ "<ins>Named&nbsp;Entities</ins></a></li>"
				+ "<ul id=\"classTree\"></ul>");
//		$("#namedEntitiesUl")
//		.append(
//				"<li id=0>"
//						+ "<ins>Named&nbsp;Entities</ins></li>"
//						+ "<ul id=\"classTree\"></ul>");
	}else if(lang == 'zh'){
		$("#namedEntitiesUl")
		.append(
//				"<li id=0><a href='#ne'>" 
				"<li id=0><a class='treeLiA' aimId='ne' href='javascript:void(0);'>" 
				+ "<ins>命名实体</ins></a></li>"
						+ "<ul id=\"classTree\"></ul>");
	}
	
	$(data).find("class")
			.each(
					function() {
						var id = $(this).children("id").text();
						var name = $(this).children("name").text();
						var uri = $(this).children("uri").text();
						$("#classTree")
						.append(
								"<li class=\"cla tooltips topc\" id="+ id
//										+ "><img src=\"/sview/icons/tree1.jpg\" /><a href='#box_"+id+"' title='"+uri+"'>"
								+ "><img src=\"/sview/icons/tree1.jpg\" /><a class='treeLiA' aimId='box_"+id+"' href='javascript:void(0);' title='"+uri+"'>"
								+ name + "</a></li>");
//						$("#classTree")
//								.append(
//										"<li class=\"cla tooltips topc\" id="
//												+ id
//												+ "><img src=\"/sview/icons/tree1.jpg\" /><ins>"
//												+ name + "</ins><span>" + uri
//												+ "</span></li>");
						var content = addChildren($(this));
						$("#classTree").append(content);
					});
	$(".treeLiA").click(function(){
		linkToBlock($(this).attr("aimId"));
	});
//	$("#0").attr("state", expanded);
//	showContent();//show all sentences of named entity and others
	var nameEntityContainer = $("<div id='ne' mid='ne' class='classBlock'></div>");
	$("#entitiesDiv").append(nameEntityContainer);
//	var neHeader = $("<div class='header'>NamedEntities</div>");
//	nameEntityContainer.append(neHeader);
	var neBody = $("<div class='blockContent'></div>");
	nameEntityContainer.append(neBody);
	
    var netree = $("#classTree");
    for(var j=0;j<netree.children("li").length;j++){
    	var classItem = $(netree.children("li")[j]);
    	showContent(classItem,"ne");
    }
    
    var showed = $(".blockContent").children("span");
    var showedSub = "";
    $(showed).each(function(){
    	var idStr = "'"+$(this).attr("id")+"'";
    	showedSub += idStr.replace("scroll", "")+",";
    });
    if(showedSub.indexOf(",", 0)>0){
    	showedSub = showedSub.substring(0, showedSub.length-1);
    }
    showClassEntity(neBody,0, showedSub);
    
    
	var otherEntityContainer = $("<div id='others' class='classBlock'></div>");
	$("#entitiesDiv").append(otherEntityContainer);
//	var otHeader = $("<div class='header'>Other Entities</div>");
//	otherEntityContainer.append(otHeader);
	var otBody = $("<div class='blockContent'></div>");
	otherEntityContainer.append(otBody);
	showClassEntity(otBody,-1);
	

}
function showContent(classItem, parentID){
	var contentBox = $("div[mid="+parentID+"]").children(".blockContent");
 	var classId = classItem.attr("id");
 	var container = $("<div class='classBlock'></div>");
	container.attr("mid",classItem.attr("id"));
	contentBox.append(container);
	container.attr("id","box_"+classItem.attr("id"));///////
	
//	var header = $("<div class='header'></div>");
//	header.html(classItem.find("a").html());
//    container.append(header);
	var body = $("<div class='blockContent'></div>");
//	var entity = $("<div class='entity'></div>")
    container.append(body);
//	container.append(entity);
	if($(classItem).next().is("ul")){
		var subtree = $(classItem).next();
		for(var i=0;i<subtree.children("li").length;i++){
			var eee = $(subtree.children("li")[i]);
			showContent($(eee),classItem.attr("id"));
		}
	}
	showClassEntity(body,classId);
}
function showClassEntity(container,classId, showedSub){
//	onLoading();
	var data = {};
	data["ds_type"] = $("#ds_type").val();
	data["ds_id"] = $("#ds_id").val();
	data["class_id"] = classId;//show named entities and others//$(item).attr('id')
	if(showedSub != null){
		data["showed_sub"] = showedSub;
	}
	$.ajax({
		url : "/sview/entitiesView",// "test.xml",//
		dataType : 'html',
		type : "post",
		async : false,
		data : data,
		success : function(data) {
//			$("#entitiesDiv").html(data);
			$(container).prepend(data);
//			closeLoading();
//			$('#entitiesDiv').animate({
			$(container).animate({	
				scrollTop : 0
			}, 0);
		}
	});
}

function addChildren(pdata) {
	// var pid = $(pdata).children("id").text();
	// var li = "#" + pid;
	var content = "<ul>";
	$(pdata).children("subclass").each(
			function() {
				var id = $(this).children("id").text();
				var name = $(this).children("name").text();
				var uri = $(this).children("uri").text();
				content += "<li class=\"cla tooltips subc\" id=" + id
//						+ "><img src=\"/sview/icons/tree1.jpg\" /><a href='#box_"+id+"' title='"+uri+"'>" + name
					+ "><img src=\"/sview/icons/tree1.jpg\" /><a class='treeLiA' aimId='box_"+id+"' href='javascript:void(0);' title='"+uri+"'>" + name
						+ "</a></li>";
				content += addChildren($(this));
			});
	content += "</ul>";
	if (content == "<ul></ul>") {
		return "";
	} else {
		return content;
	}
}
function linkToBlock(aimId){
	var aim = $("#"+aimId);
	var top = $(aim).position().top;
	$(window).scrollTop(top);
	fade($(aim).attr("id"),'#369DFF','#fff',25,1);
	fade($(aim).attr("id"),'#fff','#369DFF',25,1);
	
}
function requestClass(classId){
	var aim = $("#" + classId);
	var top = $(aim).position().top;
	$(window).scrollTop(top);
//	$(aim).css("background","red");
	fade($(aim).attr("id"),'#FFABD0','#fff',25,1);
	fade($(aim).attr("id"),'#fff','#FFABD0',25,1);
}
function requestEntity(entityId, classId){
	var aim = $("#scroll"+entityId);
	var top = $(aim).position().top;
	$(window).scrollTop(top);
	fade($(aim).attr("id"),'#369DFF','#fff',25,1);
	fade($(aim).attr("id"),'#fff','#369DFF',25,1);
}
// 分离RGB颜色 0:R | 1:G | 2:B
function parseRGB(color, type)
{
    var start, len, result;
    len = (color.length == 4)?1:2;
    start = type * len + 1;
    result = color.substr(start, len);
    if(result.length == 1) result += result;
    return parseInt(result, 16);
}

// 页面元素ID，源色彩，渐变色彩，淡入淡出步数，是否背景颜色（默认文字颜色）
function fade(id, colorSource, colorFade, fadeStep, background)
{
    var element = document.getElementById(id);

    // 分解源色彩
    var rSource = parseRGB(colorSource, 0); //红 R
    var bSource = parseRGB(colorSource, 1); //绿 G
    var gSource = parseRGB(colorSource, 2); //蓝 B

    // 分解渐变色彩
    var rFade = parseRGB(colorFade, 0);
    var bFade = parseRGB(colorFade, 1);
    var gFade = parseRGB(colorFade, 2);

    // 步数统计
    var step = 0;

    // 设置定时器
    var fadeTimer = setInterval(
        function(){

            var tmpStep = fadeStep - step;

            // 由于 floor() 计算不准确，当达到指定步数后直接赋值源色彩
            if(step < fadeStep)
            {
                with(Math)
                {
                    var rStep = floor((rSource - rFade) / tmpStep);
                    var bStep = floor((bSource - bFade) / tmpStep);
                    var gStep = floor((gSource - gFade) / tmpStep);
                }

                rFade += rStep;
                bFade += bStep;
                gFade += bStep;

                if(background)
                {
                    element.style.backgroundColor = 'rgb('+rFade+','+bFade+','+gFade+')';
                }
                else
                {
                    element.style.color = 'rgb('+rFade+','+bFade+','+gFade+')';
                }
            }
            else
            {
                if(background)
                {
                    element.style.backgroundColor = colorSource;
                }
                else
                {
                    element.style.color = colorSource;
                }

                // 清除定时器
                clearInterval(fadeTimer);
            }
            step ++;
        },
        50
    );
}